<?php

namespace Core;
use \Entity, \Implementation;

class QuickProf 
{
    protected 
    
    $output = array();
    
    private 
    
    $mem;
    
    function __construct($starttime = NULL)
    {
        if (is_null($starttime)) {
			$starttime = microtime();
		}

        $this->startTime = $starttime;
        $this->mem = memory_get_peak_usage();
        unset($starttime);
    }
    
    function __get($key) { return $this->$key; }
    
    static function getMicroTime() {
		return microtime();
	}
	
	public function gatherConsoleData() {
		$logs = \Console::getLogs();
		$sizer = new Entity\Sizer;
		$tsizer = new Entity\TimeSizer;
		
		if($logs['console']) {
			foreach($logs['console'] as $key => $log) {
				if($key == 'log') {
					$logs['console'][$key]['data'] = print_r($log['data'], true);
				}
				elseif($key == 'memory') {
					$logs['console'][$key]['data'] = $sizer($log['data']);
				}
				elseif($key == 'speed') {
					$logs['console'][$key]['data'] = $tsizer(($log['data'] - $this->startTime)*1000);
				}
			}
		}
		
		$this->output['logs'] = $logs;
	}
	
	public function gatherMemoryData()
	{
	    $sizer = new Entity\Sizer;
	    $this->output['memoryTotals'] = array(
		                            'memoryused'  => $sizer(memory_get_peak_usage() - $this->mem), /* (memory_get_peak_usage() + memory_get_usage())/2 */
		                            'memorytotal' => ini_get("memory_limit"),
		                        );
	}
	
	public function gatherSpeedData()
	{
	    $tsizer = new Entity\TimeSizer;
	    $this->output['speedTotals'] = array(
	                                'speedtotal'    => $tsizer(($this->getMicroTime() - $this->startTime), 'ms'),
		                            'speedallowed'  => ini_get("max_execution_time"),
		                        );
	}
	
	public function gatherFileData()
	{
	    $stat = new Entity\FileStat;
	    $stat(get_included_files());
	    $this->output['files'] = $stat->output['files'];
	    $this->output['fileTotals'] = $stat->summary;
	}
	
	public function gatherQueryData()
	{
	}
	
	public function getProfile(Implementation\Viewer $viewer)
	{
	    $this->gatherConsoleData();
		$this->gatherMemoryData();
		$this->gatherQueryData();
		$this->gatherSpeedData();
		$this->gatherFileData();
		
		return $viewer;
	}
	
	public function display() 
	{
	    $viewer = $this->getProfile(new Implementation\Viewer);
		$viewer->render($this->output);
		
		$viewer->__destruct();
		unset($viewer);
	}
	
	function __destruct()
	{
	    unset($this->output);
	}
}

